package com.itheima.controller;


import com.aliyun.tea.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.entity.User;
import com.itheima.service.UserService;
import com.itheima.utils.SMSSendCode;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

//    @PutMapping("/update")
//    public R<>

    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user, HttpSession session) {
        String phone = user.getPhone();
        log.info("接受到的手机号为：{}",phone);
        if (phone != null && phone.length() != 0){
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("phone:{},code:{}",phone,code);
            redisTemplate.opsForValue().set(phone,code,300, TimeUnit.SECONDS);
            try {
                //SMSSendCode.sendCode(phone,code);
            }catch (Exception e){
                e.printStackTrace();
            }
            return R.success(code);
        }
        return R.error("短息发送失败,手机号不存在");
    }

    @PostMapping("/login")
    public R login(@RequestBody User user,HttpSession session){
        log.info("登陆的信息为：{}",user);
        String phone = user.getPhone();
        String code = user.getCode();
        Object sessioncode= redisTemplate.opsForValue().get(phone);
        if (!code.equals(sessioncode)){
            log.info("您输入的手机验证码不正确");
            return R.error("您输入的手机验证码不正确");
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,phone);
        User one = userService.getOne(wrapper);
        if (one == null){
            log.info("您输入的密码为注册");
            user.setStatus(1);
            user.setName("饭客_"+phone);
            userService.save(user);
            one = user;
        }
        session.setAttribute("empId",one.getId());
        redisTemplate.delete(phone);
        return R.success("登陆成功");

    }

    @PostMapping("/loginout")
    public R<String> loginout(HttpServletRequest request){
        log.info("将要退出系统");
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }

    @PutMapping("/update")
    public R update(HttpSession session){
        log.info("修改客户信息");

        return R.success("修改成功");
    }
}
